package test.controller;

import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import test.entity.Person;
import test.service.PersonService;


@Controller
@RequestMapping(value = "/person")
public class PersonController {

	@Autowired private PersonService personService;
	
	@RequestMapping("/login")
	public String login() {
		return "login";
	}
	@RequestMapping("/dologin")
	public String doLogin(String username, String password) {
		if(Objects.equals(username, "admin") && Objects.equals(password, "admin")) {
			return "redirect:main";
		}
		return "redirect:login";
	}
	@RequestMapping("/main")
	public String main(Model model) {
		model.addAttribute("persons", this.personService.getPersons());
		return "main";
	}
	
	@RequestMapping(value = "/addPerson")
	public String addPerson(Person person) {
		personService.addPerson(person);
		return "redirect:main";
	}
	
	@RequestMapping("/addPrompt")
	public String addPrompt() {
		return "addPerson";
	}
	
	@RequestMapping(value = "/getPersons")
	@ResponseBody
	public List<Person> getPersons() {
		return personService.getPersons();
	}
	@RequestMapping(value = "/deletePerson")
	public String deletePerson(int id) {
		personService.deletePerson(id);
		return "redirect:main";
	}
	
	@RequestMapping("/updatePrompt")
	public String updatePrompt(Model model, int id) {
		model.addAttribute("person", this.personService.getPersonById(id));
		return "updatePerson";
	}
	
	@RequestMapping(value = "/updatePerson")
	public void updatePerson(Person person) {
		personService.updatePerson(person);
	}
	public PersonController() {
		// TODO Auto-generated constructor stub
	}

}
